#!/bin/bash
###############################################################################
# Please copy the folder aes_100_come_tools to sd_maker!!!
###############################################################################
# File name:
#   atlas_install.sh
#
# Description:
#     Deploy and install the atlas package in emmc.
#
# $1 - Atlas module number
#
# The atlas modules are mapped in machine as following:
# |21(F1)|22(F2)|23(F3)|24(F4)|  
# |17(E1)|18(E2)|19(E3)|20(E4)|  
# |13(D1)|14(D2)|15(D3)|16(D4)|  
# |09(C1)|10(C2)|11(C3)|12(C4)|  
# |05(B1)|06(B2)|07(B3)|08(B4)|  
# |01(A1)|02(A2)|03(A3)|04(A4)|  
#
# 1. Run the script with the module number inputed. 
# Exp: cd sd_maker/aes_100_come_tools/ 
#      ./atlas_install.sh 1  Install the package in atlas module A1.
###############################################################################
MOD_NUM=$1
SDMK_PATH=$(dirname "$PWD")
LOG_PATH=${SDMK_PATH}"/sd_card_making_log/"

chmod +x *.sh

#1. connect utx and urx
bash atlas_emmc_icp.sh $MOD_NUM connect

#2. reset and enter into icp mode
bash atlas_reset.sh $MOD_NUM

#3. ping board and detect the link status
echo "Ping"
while true
do
    ip=192.168.0.2
    echo -n "."
    ping -c 1 $ip > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo ping ok!
	break;
    fi
done

#4. deploy the package
cd ${SDMK_PATH}
rm -rf sd_card_making_log

# The default limit time for expect is 30s.
expect << EOF
    set timeout -1
    spawn python3 make_sd_card.py recover_aes100
    expect {
        "Please input Y: continue, other to install them:" {send "Y\n"}
        };
    expect eof;
EOF

echo "Please wait for the recovery process..."

# Monitor the recovery process
while true
do
    ps -ef | grep "python3 make_sd_card.py recover_aes100" | grep -v grep
    # Block when make_sd_card.py is running.
    if [ $? -ne 0 ]; then
        echo "The end of recovery process."
        break;
    fi
done

#5. judge recover status
val=$(cat ${LOG_PATH}/make_os_sd.result|grep "Success")
if [ $val == "Success" ]; then
    #6. disconnect utx and urx
    echo "Disconnect utx and urx"
    bash ${SDMK_PATH}/aes_100_come_tools/atlas_emmc_icp.sh $MOD_NUM disconnect
    #7. reset and switch the debug uart
    echo "Reset!"
    bash ${SDMK_PATH}/aes_100_come_tools/atlas_reset.sh $MOD_NUM
    if [ $MOD_NUM -lt 5 ]; then
        tty_num=4
    elif [ [ $MOD_NUM -gt 4 ] && [ $MOD_NUM -lt 9 ] ]; then
        tty_num=5
    elif [ [ $MOD_NUM -gt 8 ] && [ $MOD_NUM -lt 13 ] ]; then
        tty_num=6
    elif [ [ $MOD_NUM -gt 12 ] && [ $MOD_NUM -lt 17 ] ]; then
        tty_num=7
    elif [ [ $MOD_NUM -gt 16 ] && [ $MOD_NUM -lt 21 ] ]; then
        tty_num=8
    else
        tty_num=9
    fi
    echo "Please use /dev/ttyS$tty_num to check installation information"
elif [ $val == "Failed" ]; then
    echo "Recovery failed!!"
fi


